<template>
  <el-dialog v-model="dialogVisible" :title="title" width="800" :before-close="handleClose">
    <div class="descriptions">
      <el-descriptions title="报名课程" border :column="1">
        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">课程名称</div>
          </template>
          {{courseInfo.name}}
        </el-descriptions-item>

        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">课程内容</div>
          </template>
          <div v-if="info.approvalContent">
            <div class="selectLesson" v-for="(item, index) in info.approvalContent.selectLesson" :key="index">{{index+1}}.{{item.name}}</div>
          </div>
        </el-descriptions-item>

        <!-- 折扣价 -->
        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">课程价格</div>
          </template>
          <span>¥{{proxy.$utils.formatNumber(info.price)}}</span>
        </el-descriptions-item>

        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">订单金额</div>
          </template>
          <span>¥{{proxy.$utils.formatNumber(amountRefund)}}</span>
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="付款记录" border :column="1">
        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.pay_info">
          <template #label>
            <div class="cell-item descriptionsLabel150">{{info.signUpPrice?"预付款":"支付金额"}}</div>
          </template>
          <el-text class="mx-1" type="success">{{proxy.$utils.formatNumber(info.pay_info.pay_amount.total/100)}}</el-text>
        </el-descriptions-item>

        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.pay_info">
          <template #label>
            <div class="cell-item descriptionsLabel150">{{info.signUpPrice?"预付款时间":"支付时间"}} </div>
          </template>
          {{proxy.$utils.dateTimeFormateFn(info.pay_info.pay_time,'all')}}
        </el-descriptions-item>

        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.signUpPrice">
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款应付金额</div>
          </template>
          {{proxy.$utils.formatNumber(info.price - info.pay_info.pay_amount.total/100)}}
        </el-descriptions-item>

        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.signUpPrice">
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款实付金额</div>
          </template>
          <el-text class="mx-1" type="success" v-if="info.balance_pay_info">{{proxy.$utils.formatNumber(info.balance_pay_info.pay_amount.total / 100)}}</el-text>
        </el-descriptions-item>

        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.signUpPrice">
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款支付时间</div>
          </template>
          <div v-if="info.balance_pay_info">
            {{proxy.$utils.dateTimeFormateFn(info.balance_pay_info.pay_time,'all')}}
          </div>
        </el-descriptions-item>

        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">支付总计</div>
          </template>
          <el-text class="mx-1">{{proxy.$utils.formatNumber(info.payPrice)}}</el-text>
        </el-descriptions-item>

        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.refund_info">
          <template #label>
            <div class="cell-item descriptionsLabel150">退款金额</div>
          </template>
          <el-text class="mx-1 errColor" type="danger">{{proxy.$utils.formatNumber(info.refund_info.refund_amount.total/100)}}</el-text>
        </el-descriptions-item>
        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.refund_info">
          <template #label>
            <div class="cell-item descriptionsLabel150">退款时间</div>
          </template>
          {{proxy.$utils.dateTimeFormateFn(info.refund_info.refund_time,'all')}}
        </el-descriptions-item>
        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.refund_info">
          <template #label>
            <div class="cell-item descriptionsLabel150">退款原因</div>
          </template>
          {{info.refund_info.refundReason}}
        </el-descriptions-item>
        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.refund_info">
          <template #label>
            <div class="cell-item descriptionsLabel150">退款单号</div>
          </template>
          {{info.refund_info.refund_id}}
        </el-descriptions-item>
        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.balance_refund_info">
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款退款金额</div>
          </template>
          <el-text class="mx-1 errColor" type="danger">{{proxy.$utils.formatNumber(info.balance_refund_info.refund_amount.payer_refund / 100)}}</el-text>
        </el-descriptions-item>
        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.balance_refund_info">
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款退款时间</div>
          </template>
          {{proxy.$utils.dateTimeFormateFn(info.balance_refund_info.refund_time,'all')}}
        </el-descriptions-item>
        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.balance_refund_info">
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款退款原因</div>
          </template>
          {{info.balance_refund_info.refundReason}}
        </el-descriptions-item>
        <el-descriptions-item label-class-name="descriptionsLabel150" v-if="info.balance_refund_info">
          <template #label>
            <div class="cell-item descriptionsLabel150">尾款退款单号</div>
          </template>
          {{info.balance_refund_info.refund_id}}
        </el-descriptions-item>
        <div v-for="(item, index) in info.pay_discount_info || []" :key="index">
          <el-descriptions-item label-class-name="descriptionsLabel150">
            <template #label>
              <div class="cell-item descriptionsLabel150">优惠减免金额（{{index+1}}）</div>
            </template>
            <el-text class="mx-1 errColor" type="danger">{{proxy.$utils.formatNumber(item.info.amount.refund/100)}}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="descriptionsLabel150">
            <template #label>
              <div class="cell-item descriptionsLabel150">优惠减免时间（{{index+1}}）</div>
            </template>
            {{proxy.$utils.dateTimeFormateFn(item.info.create_time,"all")}}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="descriptionsLabel150">
            <template #label>
              <div class="cell-item descriptionsLabel150">优惠减免单号（{{index+1}}）</div>
            </template>
            {{item.info.refund_id}}
          </el-descriptions-item>
          <el-descriptions-item label-class-name="descriptionsLabel150">
            <template #label>
              <div class="cell-item descriptionsLabel150">优惠减免原因（{{index+1}}）</div>
            </template>
            {{item.info.discountReason}}
          </el-descriptions-item>
        </div>
        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">订单金额</div>
          </template>
          <el-text class="mx-1" type="primary">{{proxy.$utils.formatNumber(info.displayPrice)}}</el-text>
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="优惠减免" border :column="1">
        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">减免金额</div>
          </template>
          <el-input v-model="params.discountPrice" placeholder="请输入减免金额" type="number" />
        </el-descriptions-item>
        <el-descriptions-item label-class-name="descriptionsLabel150">
          <template #label>
            <div class="cell-item descriptionsLabel150">备注</div>
          </template>
          <el-input v-model="params.discountReason" :autosize="{ minRows:  4 }" type="textarea" placeholder="请输入减免理由" />
        </el-descriptions-item>
      </el-descriptions>

      <div class="fz16 bold">课程标签</div>
      <el-checkbox-group v-model="tags">
        <el-checkbox :label="item.id" :value="item.id" v-for="(item, index) in tagList" :key="index">
          {{item.tagname}}
        </el-checkbox>
      </el-checkbox-group>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="save" :loading="loading">
          确 认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();
const instance = getCurrentInstance();
import useCounterStore from "@/store/counter";
const counter = useCounterStore();
const emit = defineEmits(["fatherMethod"]);

let dialogVisible = ref(false);
let title = ref("");
let courseInfo = ref({}); // 课程信息
let info = ref({}); // 订单详情
let params = ref({
  orderId: "",
  discountPrice: "",
  discountReason: "",
  out_trade_no: "", //商户下单时传入的商户系统内部订单号
  balance_out_trade_no: "", //商户下单时传入的商户系统内部订单号
  total: 0, //订单总金额
});
let loading = ref(false);
let orderId;
let discountRecord = ref([]); //优惠减免记录
let tags = ref([]); //用户标签
let tagList = ref([]);
let originalTags = ref([]); //原始标签
let discountUid = ref(""); //优惠减免记录的唯一id
let moxueyuanInfo = ref({}); //魔学院信息

//一共支付的金额
let totalPaymentAmount = computed(() => {
  let params = { ...info.value };
  let total = 0;
  if (params.pay_info) {
    total += params.pay_info.pay_amount.total / 100;
  }
  if (params.balance_pay_info) {
    total += params.balance_pay_info.pay_amount.total / 100;
  }
  return total;
});

//可用于退款的金额
let amountRefund = computed(() => {
  let params = { ...info.value };
  let arr = params.pay_discount_info || [];
  let amount = 0;
  arr.forEach((element) => {
    amount += element.info.amount.refund / 100;
  });
  return totalPaymentAmount.value - amount;
});

//尾款余额
let balancePayment = computed(() => {
  let params = { ...info.value };
  if (!params.balance_pay_info) return 0;
  let total = params.balance_pay_info.pay_amount.total / 100;
  let arr = params.pay_discount_info || [];
  let amount = 0;
  arr.forEach((element) => {
    if (element.balance_out_trade_no) {
      amount += element.info.amount.refund / 100;
    }
  });
  //如果有尾款退款，则减去尾款退款金额
  if (params.balance_refund_info) {
    let newNum =
      total - params.balance_refund_info.refund_amount.payer_refund / 100;
    total = newNum;
  }
  return total - amount;
});

//记录每一笔操作，优惠减免的金额和设置标签
let newParams = computed(() => {
  let differTags = proxy.$utils.getDifferentValues(
    tags.value,
    originalTags.value
  );
  let differTagList = [];
  differTags.forEach((element) => {
    let index = proxy.$utils.findIndexByField(tagList.value, "id", element);
    differTagList.push(tagList.value[index]);
  });
  //修改魔学院的信息
  let editMoxueyuanInfo = {
    userId: moxueyuanInfo.value.userid,
    mobile: moxueyuanInfo.value.mobile,
    name: moxueyuanInfo.value.name,
    tag: tags.value,
  };
  return {
    differTagList, //去掉的标签
    discountPrice: params.value.discountPrice, //优惠金额
    discountUid: discountUid.value, //优惠id
    editMoxueyuanInfo, //魔学院信息修改
    orderId: info.value._id,
  };
});

//获取用户标签
async function getUserTags() {
  let resp = await proxy.$apis.moxueyuanFunc({
    data: { userid: info.value.userId, mobile: info.value.mobile },
    type: "getUserData",
  });
  moxueyuanInfo.value = resp;
  tagList.value = resp.tagList;
  tags.value = resp.tag;
  originalTags.value = resp.tag;
  console.log("用户详情", resp);
}

//更新魔学院信息
async function updateMoxueyuanInfo() {
  let data = {
    userId: info.value.userId,
    mobile: info.value.mobile,
    name: info.value.approvalContent.model.name,
    tag: tags.value,
  };
  await proxy.$apis.moxueyuanFunc({ type: "setUserData", data });
}

async function save() {
  try {
    loading.value = true;
    if (!params.value.discountPrice)
      return proxy.$utils.showToast("请输入减免金额", 0);
    if (Number(params.value.discountPrice) > Number(amountRefund.value))
      return proxy.$utils.showToast(`退款金额不能大于${amountRefund.value}`, 0);

    //一些必要的参数在这里补充
    let obj = {
      payType: info.value.payType,
      updateUser: counter.updateUser,
      discountUid: discountUid.value,
    };

    //尾款足够优惠
    let balanceSufficient = false;
    if (info.value.balance_pay_info) {
      if (balancePayment.value >= Number(params.value.discountPrice)) {
        balanceSufficient = true;
      }
    }

    //尾款>0 && 尾款不足优惠
    let balancePaymentInsufficient = false;
    if (info.value.balance_pay_info && balancePayment.value) {
      if (balancePayment.value < Number(params.value.discountPrice)) {
        balancePaymentInsufficient = true;
      }
    }

    let subimtData = []; //如果有尾款和预付款同时退款的情况

    //尾款足够此次优惠
    if (balanceSufficient) {
      params.value.balance_out_trade_no = info.value.balance_out_trade_no;
      params.value.total = info.value.balance_pay_info.pay_amount.total;
    } else if (balancePaymentInsufficient) {
      //尾款不足优惠
      let aa = { ...params.value };
      aa.balance_out_trade_no = info.value.balance_out_trade_no;
      aa.total = info.value.balance_pay_info.pay_amount.total;
      aa.discountPrice = balancePayment.value;
      subimtData.push(aa);

      //不足的部分拿预付款
      let bb = { ...params.value };
      bb.out_trade_no = info.value.out_trade_no;
      bb.total = info.value.pay_info.pay_amount.total;
      bb.discountPrice =
        Number(params.value.discountPrice) - balancePayment.value;
      subimtData.push(bb);
    } else {
      //从预付款退款
      params.value.out_trade_no = info.value.out_trade_no;
      params.value.total = info.value.pay_info.pay_amount.total;
    }

    //新增一条优惠减免记录
    await proxy.$apis.orderDiscountRecord({
      type: "add",
      data: newParams.value,
    });

    if (subimtData.length) {
      //return console.log("subimtData", subimtData);
      for (let index = 0; index < subimtData.length; index++) {
        const element = subimtData[index];
        let finalObj = { ...obj, ...element };
        finalObj.discountPrice = finalObj.discountPrice * 100;
        await proxy.$apis.orderRefund(finalObj);
      }
    } else {
      let query = { ...obj, ...params.value };
      query.discountPrice = query.discountPrice * 100;
      //return console.log("query", query);
      await proxy.$apis.orderRefund(query);
    }
    // updateMoxueyuanInfo(); //更新魔学院信息
    proxy.$utils.showToast("优惠减免成功");
    setTimeout(() => {
      handleClose();
    }, 500);
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
}

async function getInfo() {
  return await proxy.$apis.orderAction({
    type: "details",
    data: { _id: orderId },
  });
}

async function open(id) {
  discountUid.value = proxy.$utils.generateUUID();
  params.value.orderId = id;
  orderId = id;
  let resp = await getInfo();
  title.value = `优惠减免 - ${resp.approvalContent.model.name} - ${resp.approvalContent.model.identityCard}`;
  info.value = resp;
  getUserTags();
  //优惠减免记录
  if (resp.hasOwnProperty("discountRecord"))
    discountRecord.value = resp.discountRecord;
  console.log("订单详情", resp);
  courseInfo.value = await proxy.$apis.course({
    type: "details",
    data: { _id: resp.curriculum_id },
  });
  console.log("课程详情", courseInfo.value);
  console.log("尾款剩余", balancePayment.value);
  console.log("可用于退款的金额", amountRefund.value);
  dialogVisible.value = true;
}

async function handleClose() {
  discountUid.value = "";
  params.value = {
    orderId: "",
    discountPrice: "",
    discountReason: "",
    out_trade_no: "", //商户下单时传入的商户系统内部订单号
    balance_out_trade_no: "", //商户下单时传入的商户系统内部订单号
    total: 0, //订单总金额
  };
  courseInfo.value = {};
  moxueyuanInfo.value = {};
  info.value = {};
  tags.value = [];
  originalTags.value = [];
  tagList.value = [];
  await getInfo();
  emit("fatherMethod");
  orderId = null;
  dialogVisible.value = false;
}

defineExpose({ open });
</script>



<style lang="scss" scoped>
.container {
  padding: 15px;

  .el-card {
    margin-bottom: 15px;
  }
}
.descriptions {
  max-height: 70vh;
  overflow-y: auto;
}
.el-descriptions {
  margin-bottom: 20px;
}
.mx-1 {
  font-weight: bold;
}
.selectLesson {
  border-bottom: 1px solid #dcdfe6;
  padding: 10px 0;
}
.selectLesson:last-child {
  border-bottom: none;
}
</style>


